package edu;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.datanucleus.jpa.annotations.PersistenceAware;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import edu.objects.Board;

/**
 * This servlet is to handle the user join game process 
 * 
 * in this join handler class, we are going to use the session, which key is "board" and the value is
 * the Board class to store our game status
 * 
 * if we receive the post from 
 */

public class JoinHandler extends HttpServlet 
{
	/**
	 * function to deal with get request. When a request send to the server, which defined 
	 * as get method. This function will be called by the server. Here we can simply call
	 * doPost
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException 
	{
		// simply call doPost
		this.doPost(req, resp);
	}
	
	/**
	 * receive the request from client side, then to process the join game flow
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
	
		// check if we got the post value
		
		String player = (String) req.getParameter("name");
		
		
		
		
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Board board;
		
		
		try
		{
			board = pm.getObjectById(Board.class, "board");
			board.addPlayer(player);
			
			 
			
		}
		catch(javax.jdo.JDOObjectNotFoundException e)
		{
			Key key = KeyFactory.createKey(Board.class.getSimpleName(), "board");
			
			board = new Board();
			
			board.addPlayer(player);
			
			board.setKey(key);
			
			pm.makePersistent(board);
			 
			
			
		}
		finally
		{
			pm.close();
		}
		
		resp.sendRedirect("/game.jsp");
		
		
	}

}
